<template>
  <div class="collaboration-panel">
    <!-- 协作者头像栏 -->
    <div class="collaborators-bar">
      <transition-group name="avatar" tag="div" class="avatar-list">
        <div
          v-for="user in activeUsers"
          :key="user.id"
          class="avatar-item"
          :style="{ borderColor: user.color }"
          @click="focusUser(user)"
        >
          <el-tooltip :content="`${user.name} - ${user.status}`" placement="bottom">
            <el-avatar :size="36" :src="user.avatar" :style="{ background: user.color }">
              {{ user.name.charAt(0) }}
            </el-avatar>
          </el-tooltip>
          <div class="status-dot" :class="user.status"></div>
        </div>
      </transition-group>
      
      <el-button
        circle
        size="small"
        @click="showCollaborationPanel = true"
        :badge="activeUsers.length"
      >
        <el-icon><User /></el-icon>
      </el-button>
    </div>

    <!-- 协作侧边栏 -->
    <el-drawer
      v-model="showCollaborationPanel"
      title="协作面板"
      direction="rtl"
      size="400px"
    >
      <div class="collaboration-content">
        <!-- 在线用户 -->
        <div class="section">
          <div class="section-title">
            <span>在线用户 ({{ activeUsers.length }})</span>
            <el-button text @click="inviteUsers">
              <el-icon><Plus /></el-icon>
              邀请
            </el-button>
          </div>
          
          <div class="user-list">
            <div
              v-for="user in activeUsers"
              :key="user.id"
              class="user-item"
            >
              <el-avatar :size="40" :src="user.avatar" :style="{ background: user.color }">
                {{ user.name.charAt(0) }}
              </el-avatar>
              
              <div class="user-info">
                <div class="user-name">{{ user.name }}</div>
                <div class="user-activity">{{ user.currentActivity }}</div>
              </div>
              
              <div class="user-actions">
                <el-tag :type="getStatusType(user.status)" size="small">
                  {{ user.status }}
                </el-tag>
                <el-dropdown>
                  <el-button text circle size="small">
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="followUser(user)">
                        <el-icon><View /></el-icon>
                        跟随视图
                      </el-dropdown-item>
                      <el-dropdown-item @click="chatWithUser(user)">
                        <el-icon><ChatDotRound /></el-icon>
                        发起聊天
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>
        </div>

        <!-- 实时游标 -->
        <div class="section">
          <div class="section-title">实时游标</div>
          <el-switch
            v-model="showCursors"
            active-text="显示"
            inactive-text="隐藏"
          />
        </div>

        <!-- 变更历史 -->
        <div class="section">
          <div class="section-title">变更历史</div>
          <el-timeline>
            <el-timeline-item
              v-for="(change, index) in recentChanges"
              :key="index"
              :timestamp="formatTime(change.timestamp)"
              :color="change.userColor"
              size="large"
            >
              <div class="change-item">
                <el-avatar :size="24" :style="{ background: change.userColor }">
                  {{ change.userName.charAt(0) }}
                </el-avatar>
                <div class="change-content">
                  <span class="change-user">{{ change.userName }}</span>
                  <span class="change-action">{{ change.action }}</span>
                  <span class="change-target">{{ change.target }}</span>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>

        <!-- 评论 -->
        <div class="section">
          <div class="section-title">
            <span>评论 ({{ comments.length }})</span>
            <el-button text @click="addComment">
              <el-icon><ChatLineSquare /></el-icon>
              添加
            </el-button>
          </div>
          
          <div class="comment-list">
            <div
              v-for="comment in comments"
              :key="comment.id"
              class="comment-item"
            >
              <el-avatar :size="32" :src="comment.avatar">
                {{ comment.userName.charAt(0) }}
              </el-avatar>
              
              <div class="comment-content">
                <div class="comment-header">
                  <span class="comment-user">{{ comment.userName }}</span>
                  <span class="comment-time">{{ formatTime(comment.timestamp) }}</span>
                </div>
                <div class="comment-text">{{ comment.text }}</div>
                
                <div class="comment-actions">
                  <el-button text size="small" @click="replyComment(comment)">
                    回复
                  </el-button>
                  <el-button
                    text
                    size="small"
                    :type="comment.resolved ? 'success' : ''"
                    @click="toggleResolve(comment)"
                  >
                    {{ comment.resolved ? '已解决' : '标记解决' }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 协作光标 -->
    <div v-if="showCursors" class="cursors-container">
      <div
        v-for="cursor in remoteCursors"
        :key="cursor.userId"
        class="remote-cursor"
        :style="{
          left: cursor.x + 'px',
          top: cursor.y + 'px',
          borderColor: cursor.color
        }"
      >
        <div class="cursor-label" :style="{ background: cursor.color }">
          {{ cursor.userName }}
        </div>
      </div>
    </div>

    <!-- 添加评论对话框 -->
    <el-dialog
      v-model="showCommentDialog"
      title="添加评论"
      width="500px"
    >
      <el-input
        v-model="newComment"
        type="textarea"
        :rows="4"
        placeholder="输入你的评论..."
      />
      <template #footer>
        <el-button @click="showCommentDialog = false">取消</el-button>
        <el-button type="primary" @click="submitComment">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  User,
  Plus,
  MoreFilled,
  View,
  ChatDotRound,
  ChatLineSquare
} from '@element-plus/icons-vue'

// 模拟WebSocket连接
let ws = null

const showCollaborationPanel = ref(false)
const showCursors = ref(true)
const showCommentDialog = ref(false)
const newComment = ref('')

// 在线用户
const activeUsers = ref([
  {
    id: 1,
    name: '张三',
    avatar: '',
    color: '#667eea',
    status: 'editing',
    currentActivity: '正在编辑表单设计器'
  },
  {
    id: 2,
    name: '李四',
    avatar: '',
    color: '#f093fb',
    status: 'viewing',
    currentActivity: '正在查看页面设计器'
  },
  {
    id: 3,
    name: '王五',
    avatar: '',
    color: '#4facfe',
    status: 'idle',
    currentActivity: '空闲中'
  }
])

// 远程光标
const remoteCursors = ref([
  { userId: 1, userName: '张三', x: 100, y: 200, color: '#667eea' },
  { userId: 2, userName: '李四', x: 300, y: 150, color: '#f093fb' }
])

// 最近变更
const recentChanges = ref([
  {
    userId: 1,
    userName: '张三',
    userColor: '#667eea',
    action: '添加了',
    target: '文本输入框',
    timestamp: new Date().getTime() - 120000
  },
  {
    userId: 2,
    userName: '李四',
    userColor: '#f093fb',
    action: '修改了',
    target: '表单标题',
    timestamp: new Date().getTime() - 300000
  },
  {
    userId: 3,
    userName: '王五',
    userColor: '#4facfe',
    action: '删除了',
    target: '下拉选择框',
    timestamp: new Date().getTime() - 600000
  }
])

// 评论
const comments = ref([
  {
    id: 1,
    userId: 1,
    userName: '张三',
    avatar: '',
    text: '这个表单的布局需要调整一下',
    timestamp: new Date().getTime() - 3600000,
    resolved: false
  },
  {
    id: 2,
    userId: 2,
    userName: '李四',
    avatar: '',
    text: '建议添加更多的验证规则',
    timestamp: new Date().getTime() - 7200000,
    resolved: true
  }
])

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    editing: 'success',
    viewing: 'info',
    idle: 'warning'
  }
  return types[status] || 'info'
}

// 格式化时间
const formatTime = (timestamp) => {
  const now = new Date().getTime()
  const diff = now - timestamp
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  return `${Math.floor(diff / 86400000)}天前`
}

// 聚焦用户
const focusUser = (user) => {
  ElMessage.info(`正在跟随 ${user.name} 的视图...`)
}

// 邀请用户
const inviteUsers = () => {
  ElMessage.info('邀请功能开发中...')
}

// 跟随用户
const followUser = (user) => {
  ElMessage.success(`开始跟随 ${user.name}`)
}

// 与用户聊天
const chatWithUser = (user) => {
  ElMessage.info(`与 ${user.name} 的聊天功能开发中...`)
}

// 添加评论
const addComment = () => {
  showCommentDialog.value = true
}

// 提交评论
const submitComment = () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  comments.value.unshift({
    id: Date.now(),
    userId: 0,
    userName: '我',
    avatar: '',
    text: newComment.value,
    timestamp: new Date().getTime(),
    resolved: false
  })
  
  newComment.value = ''
  showCommentDialog.value = false
  ElMessage.success('评论已添加')
}

// 回复评论
const replyComment = (comment) => {
  ElMessage.info('回复功能开发中...')
}

// 切换解决状态
const toggleResolve = (comment) => {
  comment.resolved = !comment.resolved
  ElMessage.success(comment.resolved ? '已标记为解决' : '已取消解决')
}

// 初始化WebSocket连接
const initWebSocket = () => {
  // 这里应该连接到实际的WebSocket服务器
  // ws = new WebSocket('ws://localhost:8080/collaboration')
  
  // ws.onmessage = (event) => {
  //   const data = JSON.parse(event.data)
  //   handleWebSocketMessage(data)
  // }
  
  // 模拟接收消息
  setInterval(() => {
    // 模拟光标移动
    remoteCursors.value.forEach(cursor => {
      cursor.x = Math.random() * 800
      cursor.y = Math.random() * 600
    })
  }, 2000)
}

// 处理WebSocket消息
const handleWebSocketMessage = (data) => {
  switch (data.type) {
    case 'cursor':
      updateRemoteCursor(data)
      break
    case 'change':
      addChange(data)
      break
    case 'user_join':
      addUser(data.user)
      break
    case 'user_leave':
      removeUser(data.userId)
      break
  }
}

// 更新远程光标
const updateRemoteCursor = (data) => {
  const cursor = remoteCursors.value.find(c => c.userId === data.userId)
  if (cursor) {
    cursor.x = data.x
    cursor.y = data.y
  } else {
    remoteCursors.value.push({
      userId: data.userId,
      userName: data.userName,
      x: data.x,
      y: data.y,
      color: data.color
    })
  }
}

// 添加变更
const addChange = (data) => {
  recentChanges.value.unshift(data)
  if (recentChanges.value.length > 20) {
    recentChanges.value.pop()
  }
}

// 添加用户
const addUser = (user) => {
  if (!activeUsers.value.find(u => u.id === user.id)) {
    activeUsers.value.push(user)
    ElMessage.success(`${user.name} 加入了协作`)
  }
}

// 移除用户
const removeUser = (userId) => {
  const index = activeUsers.value.findIndex(u => u.id === userId)
  if (index > -1) {
    const user = activeUsers.value[index]
    activeUsers.value.splice(index, 1)
    ElMessage.info(`${user.name} 离开了协作`)
  }
}

// 发送本地光标位置
const sendCursorPosition = (event) => {
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({
      type: 'cursor',
      x: event.clientX,
      y: event.clientY
    }))
  }
}

onMounted(() => {
  initWebSocket()
  
  // 监听鼠标移动
  document.addEventListener('mousemove', sendCursorPosition)
})

onUnmounted(() => {
  if (ws) {
    ws.close()
  }
  
  document.removeEventListener('mousemove', sendCursorPosition)
})
</script>

<style scoped>
.collaboration-panel {
  position: relative;
}

/* 协作者头像栏 */
.collaborators-bar {
  position: fixed;
  top: 70px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 1000;
}

.avatar-list {
  display: flex;
  gap: -8px;
}

.avatar-item {
  position: relative;
  border: 2px solid white;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.2s;
}

.avatar-item:hover {
  transform: translateY(-2px);
  z-index: 10;
}

.status-dot {
  position: absolute;
  bottom: 2px;
  right: 2px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  border: 2px solid white;
}

.status-dot.editing {
  background: #67c23a;
}

.status-dot.viewing {
  background: #409eff;
}

.status-dot.idle {
  background: #e6a23c;
}

/* 协作内容 */
.collaboration-content {
  padding: 20px 0;
}

.section {
  margin-bottom: 30px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

/* 用户列表 */
.user-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 8px;
  transition: all 0.2s;
}

.user-item:hover {
  background: #ecf5ff;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.user-activity {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 变更历史 */
.change-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.change-content {
  font-size: 13px;
  color: #606266;
}

.change-user {
  font-weight: 500;
  color: #303133;
}

.change-action {
  margin: 0 4px;
}

.change-target {
  color: #409eff;
}

/* 评论 */
.comment-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.comment-item {
  display: flex;
  gap: 12px;
}

.comment-content {
  flex: 1;
  min-width: 0;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.comment-user {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-text {
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
}

.comment-actions {
  display: flex;
  gap: 8px;
}

/* 远程光标 */
.cursors-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 9998;
}

.remote-cursor {
  position: absolute;
  width: 20px;
  height: 20px;
  border-left: 2px solid;
  border-top: 2px solid;
  transition: all 0.1s linear;
  pointer-events: none;
}

.cursor-label {
  position: absolute;
  top: 20px;
  left: 0;
  padding: 2px 8px;
  color: white;
  font-size: 12px;
  white-space: nowrap;
  border-radius: 4px;
}

/* 头像动画 */
.avatar-enter-active,
.avatar-leave-active {
  transition: all 0.3s;
}

.avatar-enter-from {
  opacity: 0;
  transform: scale(0);
}

.avatar-leave-to {
  opacity: 0;
  transform: scale(0);
}
</style>

